from datetime import date, datetime
import json
import time
import asyncio
import os
import difflib
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from playwright.sync_api import sync_playwright
# import webbrowser

def compare_files(file1_path, file2_path):
    # 读取文件内容
    with open(file1_path, "r", encoding="utf-8") as file1, open(file2_path, "r", encoding="utf-8") as file2:
        file1_lines = file1.readlines()
        file2_lines = file2.readlines()

    # 使用 difflib 比较差异
    diff = difflib.Differ()
    diff_result = list(diff.compare(file1_lines, file2_lines))

    # 提取变化的部分
    changes = []
    file1_line_num = 1
    file2_line_num = 1
    
    for line in diff_result:
        if line.startswith("- "):
            changes.append(f"{file1_line_num}: {line.strip()}")
            file1_line_num += 1
        elif line.startswith("+ "):
            changes.append(f"{file2_line_num}: {line.strip()}")
            file2_line_num += 1
        else:
            file1_line_num += 1
            file2_line_num += 1
    if len(changes) == 0:
        return None
    # 将变化部分格式化为HTML
    html_changes = "<h2>文件变化部分</h2><pre>"
    for change in changes:
        if "- " in change:
            html_changes += f"<span style='color:red;'>{change}</span><br>"
        elif "+" in change:
            html_changes += f"<span style='color:green;'>{change}</span><br>"
    html_changes += "</pre>"

    return html_changes
    
def send_email(html_content, to_email, subject="File Comparison Result"):
    # 邮件服务器配置
    smtp_server = "smtp.qq.com"  # 替换为你的SMTP服务器
    smtp_port = 587  # 替换为你的SMTP端口
    smtp_user = "291695377@qq.com"  # 替换为你的邮箱
    smtp_password = "bhecyaqfyhodbiia"  # 替换为你的邮箱密码

    # 创建邮件对象
    msg = MIMEMultipart()
    msg["From"] = smtp_user
    msg["To"] = to_email
    msg["Subject"] = subject
    # print('html_content',html_content)
    # 添加 HTML 内容
    html_part = MIMEText(html_content, "html")
    msg.attach(html_part)

    # 发送邮件
    try:
        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()  # 启用TLS加密
            server.login(smtp_user, smtp_password)
            server.sendmail(smtp_user, to_email, msg.as_string())
        print("邮件已成功发送到", to_email)
    except Exception as e:
        print("发送邮件时出错:", e)

def load_cfg(file):
    with open(file, "r", encoding="utf-8") as f:
        return json.load(f)

def get_page_content(page_url):
    with sync_playwright() as p:
        # 启动浏览器（非无头模式，方便观察）
        browser = p.chromium.launch(headless=True,timeout=60000)
        page = browser.new_page()
        # 打开目标网页
        page.goto(page_url)
        # 等待页面加载完成
        page.wait_for_load_state("networkidle")
        # 提取网页标题
        title = page.title()
        # print(f"网页标题: {title}")

        # 获取 <body> 标签的文本内容
        body_element = page.query_selector("body")
        body_text = ""
        if body_element:
            body_text = body_element.inner_text() or ""
            # print(f"网页正文内容: {body_text}")
        else:
            print("未找到 <body> 标签。")

        # 关闭浏览器
        browser.close()
        return body_text

# # 调用函数
# body_text = get_page_content(url)
# with open('test.txt','w',encoding='utf-8') as f:
#     f.write(body_text)

def save_file(content:str, file_path:str):
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)


def gas_last_file(title:str):
    #  获取最新的文件
    files = os.listdir(f"./history/{title}")
    if len(files) == 0:
        return None
    files.sort(reverse=True)

    file_path = f"./history/{title}/{files[0]}"
    if os.path.exists(file_path):
        return file_path
    else:
        return None

def check(watch):
    # obj = load_cfg("setting.json")
    # # print(obj)
    # for watch in obj["watchs"]:
        # print(watch)
    # print(watch["url"])

    content = get_page_content(watch["url"])
    temp_path = f"./{watch['title']}_temp.txt"
    save_file(content, temp_path)
    # 获取当前日期和时间
    now = datetime.now()
    # 格式化为年月日时分秒格式
    formatted_time = now.strftime("%Y%m%d-%H-%M-%S")
    # print("当前时间：", formatted_time)
    file_path = f"./history/{watch['title']}/{formatted_time}.txt"
    # print(watch["interval"])
    last = gas_last_file(watch['title'])

    # print(f"last:{last}")
    if(last):
        htmlstr = compare_files(last, temp_path)
        print(f"htmlstr:{htmlstr}")
        if htmlstr:
            save_file(content, file_path)
            send_email(htmlstr, "291695377@qq.com" , f"site changed [{watch['title']}]")
        else:
            print(f"no change [{watch['title']}]")
    else:
        save_file(content, file_path)
    os.remove(temp_path)


def main():
    # print(obj)
    # try:
    watchMap = {}
    while True:
        obj = load_cfg("setting.json")
        print('dadwa',len(obj['watchs']))
        for watch in obj["watchs"]:
            title = watch['title']
            print("title",type(title))
            if(title not in watchMap):
                last_watch_time = watchMap[title] = datetime.now()
            else:
                last_watch_time = watchMap[title]
            while True:
                if watch["interval"] == 0:
                    check(watch)
                else:
                    now = datetime.now()
                    if last_watch_time is None or (now - last_watch_time).total_seconds() >= watch["interval"]:
                        print(f"check {title} {now}sec")
                        check(watch)
                        watchMap[title] = now
        time.sleep(1)
    # except KeyboardInterrupt:
    #     print("\n程序已通过 Ctrl+C 停止。")

if __name__ == "__main__":
    main()